<?php
// +----------------------------------------------------------------------
// | HkCms 搜索页
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2021 http://www.hkcms.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: HkCms team <admin@hkcms.cn>
// +----------------------------------------------------------------------

declare (strict_types=1);

namespace app\index\controller;

use app\admin\model\cms\Model;

class Search extends BaseController
{
    public function index()
    {
        $param['keyword'] = $this->request->param('keyword','');
        $param['model_id'] = $this->request->param('model_id','', 'intval');

        $map = [['status','=','normal']];
        if (empty($param['keyword'])) {
            $this->error(lang('Please input keywords'));
        }
        $map[] = ['title','like',"%{$param['keyword']}%"];
        if (empty($param['model_id'])) {  // 没有指定模型ID时，默认从模型里取一条
            $param['model_id'] = Model::where(['status'=>'normal','is_search'=>1])->order('controller')->value('id');
            if (empty($param['model_id'])) {
                return $this->view->fetch('index/search', ['__SDATA__'=>[],'__SPAGE__'=>[],'__modelInfo__'=>[]]);
            }
        }
        $map[] = ['model_id','=',$param['model_id']];

        $model = Model::where(['id'=>$param['model_id']])->find();
        if (empty($model)) {
            $this->error(lang('Model doesn\'t exist!'));
        }

        // 搜索查询
        $c = '\app\admin\model\cms\\'.$model->controller;
        $obj = (new $c)->setTable($model->tablename)
            ->with(['category'])
            ->where($map)
            ->append(['publish_time_text','url'])
            ->paginate([
                'list_rows'=> 10,
                'var_page' => 'page',
                'query' => $param
            ], false);

        $array = $obj->toArray()['data'];
        $page = $obj;

        $modelInfo = Model::where(['status'=>'normal','is_search'=>1])->order('controller')->select()->toArray();
        return $this->view->fetch('index/search', [
            '__SDATA__'=>$array,
            '__SPAGE__'=>$page,
            '__modelInfo__'=>$modelInfo,
            '__param__'=>$param,
        ]);
    }
}